<slot/> forwarding
Posted on 2023-04-22 by
henrikvilhelmberglundWhat is slot forwarding ?
In this example we want to have two divs with the attribute slot="header". However this is impossible because slot attributes need to be unique .
We can fix this by using a {"<"}svelte:fragment>
tag instead.
B header:
C header:
Header from A
C header:
Header from B
Header from B
C content:
C footer: <script>
import C from "./C.svelte";
</script>
B header: <slot name="b-header" />
<br />
<C>
<svelte:fragment slot="header">
<div>Header from B</div>
<div>Header from B</div>
</svelte:fragment>
</C>
<style>
</style>
In the next example we have three buttons. Clicking any of them will increase the sum.
Here we don't have props in the components script tags but instead in the slots.
C header:
Header from A 0
C content:
C footer: <script>
import B2 from "./B2.svelte";
let a = 0;
</script>
<button on:click={() => a++}>A: {a}</button>
<B2>
<div slot="header" let:sum>Header from A {sum + a}</div>
</B2>